package yxm.zyf.love.datastructure;

import java.util.*;

public class MapTest {
    public static HashMap sensitiveWordMap;

    public static void main(String[] args) {
        HashMap map;
        HashMap mapA =new HashMap(16);
        HashMap mapB =new HashMap(16);

        map = mapA;
        map.put("s1","1");

        System.out.println("map = " + map);
        System.out.println("mapA = " + mapA);

        mapA = mapB;
        System.out.println("map = " + map);
        System.out.println("mapA = " + mapA);
        System.out.println("mapB = " + mapB);

        mapA.put("s2","2");
        System.out.println("map = " + map);
        System.out.println("mapA = " + mapA);
        System.out.println("mapB = " + mapB);

        Set<String> set = new HashSet<>();
        set.add("123");
        set.add("456");set.add("789");set.add("120");
        addSensitiveWordToHashMap(set);
        System.out.println("sensitiveWordMap = " + sensitiveWordMap);
    }


    private static void addSensitiveWordToHashMap(Set<String> keyWordSet) {
        //初始化敏感词容器，减少扩容操作
        sensitiveWordMap = new HashMap(keyWordSet.size());
        String key;
        Map nowMap;
        Map<String, String> newWorMap;
        //迭代keyWordSet
        Iterator<String> iterator = keyWordSet.iterator();
        while (iterator.hasNext()) {
            //关键字
            key = iterator.next();
            nowMap = sensitiveWordMap;
            for (int i = 0; i < key.length(); i++) {
                char keyChar = key.charAt(i);
                //转换成char型
                Object wordMap = nowMap.get(keyChar);
                if (wordMap != null) {
                    //如果存在该key，直接赋值
                    nowMap = (Map) wordMap;
                } else {
                    //不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
                    newWorMap = new HashMap<String, String>();
                    newWorMap.put("isEnd", "0");
                    //不是最后一个
                    nowMap.put(keyChar, newWorMap);
                    nowMap = newWorMap;
                }
                if (i == key.length() - 1) {
                    //最后一个
                    nowMap.put("isEnd", "1");
                }
                System.out.println("nowMap = " + nowMap);
            }
        }
    }
}
